package com.cskaoyan.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 创建日期: 2022/07/06 10:11
 *
 * @author ciggar
 */
public class MybatisUtils {

    static SqlSession sqlSession;

    static {


        // 1. 读取核心配置文件
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 2. 获取SqlSessionFactory对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(in);


        // 3. 获取SqlSession，本质上其实就是connection对象的一个包装类
        sqlSession = sqlSessionFactory.openSession(true);


    }



    // 获取sqlSession的方法
    public static SqlSession getSqlSession(){
        return sqlSession;
    }
}
